package com.sbtr.impl;


import com.alibaba.fastjson.JSONObject;
import com.sbtr.business.calibration.service.ICalibrationDetailsService;
import com.sbtr.business.calibration.service.ICalibrationFileService;
import com.sbtr.business.calibration.service.ICalibrationImgService;
import com.sbtr.business.calibration.service.ICalibrationService;
import com.sbtr.constant.CalibrationConstant;
import com.sbtr.open.calibration.dto.*;
import com.sbtr.util.ImageOperUtil;
import com.sbtr.util.ZipUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.*;

/**
 * 标注图片处理service
 *
 * @author zengjw5
 */
@Service
public class CalibrationPictureCommon {

    private static final Logger logger = LoggerFactory.getLogger(CalibrationPictureCommon.class);

    @Value("${oss.config.uploadPath}")
    private String uploadPath;

    /**
     * 缩略图宽度
     */
    @Value("${material.picture.upload.thumbnailWide:600}")
    private int thumbnailWide;

    /**
     * 缩略图高度
     */
    @Value("${material.picture.upload.thumbnailHeight:400}")
    private int thumbnailHeight;

    @Autowired
    private ICalibrationFileService calibrationFileService;

    @Autowired
    private ICalibrationImgService calibrationImgService;

    @Autowired
    private ICalibrationDetailsService calibrationDetailsService;

    @Autowired
    private ICalibrationService calibrationService;


    /**
     * 物体检测的图片保存
     * 1.解压zip包，生成文件夹
     * 2.生成缩略图文件夹和生成缩略图
     * 3.每张图片（CalibrationImgDto）入库，有原图路径和缩略图路径
     * 4.解压路径下生成json.txt
     *
     * @param calibrationDto
     * @param calibrationFileDto
     * @return
     */
    public CalibrationDto unzipAndSaveObjectDetectionPicture(CalibrationDto calibrationDto, CalibrationFileDto calibrationFileDto, String finisher) throws Exception {
//		try {
        List<CalibrationImgDto> calibrationImgDtos = new ArrayList<>();
        // 文件上传完成：1、解压压缩包，2、将每张图片调用图片保存器重新保存3、记录图片信息
        String bucketDir = calibrationFileDto.getBucketDir();//压缩包所在目录
        String filename2 = calibrationFileDto.getFileName2();//原压缩包文件名
        File zip = new File(bucketDir + File.separator + filename2);//压缩包路径
        String unZipTmp = bucketDir + File.separator + filename2 + "_unzip";// 压缩包解压路径
        ZipUtil.unZip(zip, unZipTmp);//解压完成...

        //对解压目标文件夹里面的图片进行处理
        File unZipTmpFile = new File(unZipTmp);
        File[] listFiles = unZipTmpFile.listFiles();
        if (listFiles == null || listFiles.length == 0) {
            throw new Exception("压缩包为空");
        } else if (listFiles.length == 1 && listFiles[0].isDirectory()) {//解压出来后，如果里面只有一个文件夹
            // 解压出来后目标文件夹里面是一个文件夹(选择一个文件夹进行压缩时, 图片在所选文件夹里)
            File[] listFiles2 = listFiles[0].listFiles();
            if (listFiles2 == null || listFiles2.length == 0) {
                throw new Exception("压缩包为空");
            } else if (listFiles2.length != 1 && listFiles2[0].isDirectory()) {
                throw new Exception("压缩包里存在多个文件夹，请把所有图片放在一个文件夹里");
            }
            for (File file : listFiles2) {
                // 是图片文件才处理
                if (file.isFile() && ImageOperUtil.isImage(file.getName())) {
                    try (InputStream fIn = new FileInputStream(file);) {
                        CalibrationImgDto dto = saveThumbnailPicture(calibrationDto, calibrationFileDto, fIn, file.getName(), listFiles[0].getAbsolutePath());
                        if (dto != null) {
                            calibrationImgDtos.add(dto);
                        }
                    }
                }
                //file.delete(); // 处理完成删除文件
            }
            //listFiles[0].delete();
        } else if (listFiles.length != 1 && listFiles[0].isDirectory()) {
            throw new Exception("压缩包里存在多个文件夹，请把所有图片放在一个文件夹里");
        } else {
            // 解压出来后多个文件夹目标文件夹里是图片文件(选择所有图片进行压缩时)
            for (File file : listFiles) {
                // 是图片文件才处理，生成缩略图
                if (file.isFile() && ImageOperUtil.isImage(file.getName())) {
                    /**
                     * 1.生成缩略图
                     * 2.生成对应的CalibrationImgDto,保存缩略图路径（需要关联calibrationFileDto）
                     * 3.在压缩目录下，生成json.txt文件
                     * 4.
                     */
                    InputStream fIn = new FileInputStream(file);
                    CalibrationImgDto dto = saveThumbnailPicture(calibrationDto, calibrationFileDto, fIn, file.getName(), unZipTmpFile.getAbsolutePath());
                    if (dto != null) {
                        calibrationImgDtos.add(dto);
                    }
                    fIn.close();
                }
                //file.delete(); // 原图文件不删
            }
        }

        // 解压文件夹不删
        //unZipTmpFile.delete();
        zip.delete();//解压完，删除zip包（有待商榷）
        //TODO 任务分配，计算出需要分配任务的人
        // 更新每人的接受任务CalibrationDetails
        List<CalibrationDetailsDto> tasks = calibrationService.divisionImgDetectTask(calibrationDto.getId(), finisher);

        String[] finisherArr = null;
        if (StringUtils.isEmpty(finisher)) {
            finisherArr = calibrationDto.getFinisher().split(",");
        } else {
            finisherArr = finisher.split(",");
        }

        //用子任务来分配素材
        int userlength = tasks.size();
        Map<Long, Long> taskcount = new HashMap<>();
        for (int i = 0; i < calibrationImgDtos.size(); i++) {
            if (userlength > 1) {
                int j = i % userlength;
                calibrationImgDtos.get(i).setFinisher(tasks.get(j).getFinisher());//分配任务负责人
                calibrationImgDtos.get(i).setCalibrationDetailId(tasks.get(j).getId());//子任务id
                taskcount.put(tasks.get(j).getId(), null == taskcount.get(tasks.get(j).getId()) ? 1 : taskcount.get(tasks.get(j).getId()) + 1);//计数
            } else {
                calibrationImgDtos.get(i).setFinisher(tasks.get(0).getFinisher());//分配任务负责人
                calibrationImgDtos.get(i).setCalibrationDetailId(tasks.get(0).getId());//子任务id
                taskcount.put(tasks.get(0).getId(), null == taskcount.get(tasks.get(0).getId()) ? 1 : taskcount.get(tasks.get(0).getId()) + 1);//计数
            }
        }

        logger.info("@@@@@@@ taskcount:\\n" + JSONObject.toJSONString(taskcount));
        //TODO 更新子任务的素材数量
        updateImgDetectTaskCount(tasks, taskcount);
        //在解压目录下，生成json.txt文件
        File file = new File(unZipTmp + File.separator + "json.txt");
        if (!file.exists()) {
            file.createNewFile();
        }

        //保存分割后的素材calibrationImgDto
        boolean tag = false;
        if (!calibrationImgDtos.isEmpty()) {
            tag = calibrationImgService.batchSave(calibrationImgDtos);
        }
        if (tag) {
            // 更新总的发布任务
            CalibrationDto calibration = calibrationService.findById(calibrationDto.getId());
            //查询子任务的成员，更新成员列表
            List<CalibrationDetailsDto> slaveTasks = calibrationDetailsService.searchDetailsCalibrationId(calibration.getId());
            Set<String> members = new HashSet<>();
            slaveTasks.stream().forEach(task -> {
                members.add(task.getFinisher());
            });
            String allMembers = StringUtils.join(members, ",");
            if (calibration.getCompleted() == null) {
                calibration.setCompleted(0);
            }
            calibration.setTotalCount(calibration.getTotalCount() == null ? calibrationImgDtos.size() : calibration.getTotalCount() + calibrationImgDtos.size());//素材总数
            calibration.setFinisher(allMembers);//任务接收人
            calibration.setStatus(CalibrationConstant.TASK_STATUS_CALIBRATING);
            calibration.setUpdateTime(new Date());
            return calibrationService.update(calibration);
        }
//			return tag;
//		} catch (IllegalArgumentException e) {
//			logger.error("上传图片异常", e);
//			String message = e.getMessage();
//			if ("图片名称太长".equals(message)) {
//				throw e;
//			}
//		} catch (IOException e) {
//			logger.error("上传zip文件异常", e);
//		}
        return null;
    }

    private void updateImgDetectTaskCount(List<CalibrationDetailsDto> tasks, Map<Long, Long> taskcount) {
        tasks.stream().forEach(task -> {
            long count = taskcount.get(task.getId());
            if (null == task.getTotalCount()) {
                task.setTotalCount((int) count);//
            } else {
                task.setTotalCount(task.getTotalCount() + (int) count);//数量叠加
            }

            calibrationDetailsService.update(task);
            logger.info("分配子任务素材成功，id[{}]={}", task.getId(), count);
        });
    }

    public boolean unzipAndSavePicture(CalibrationDto calibrationDto, CalibrationFileDto calibrationFileDto, String finisher) throws Exception {
//		try {
        List<CalibrationImgDto> calibrationImgDtos = new ArrayList<>();
        // 文件上传完成：1、解压压缩包，2、将每张图片调用图片保存器重新保存3、记录图片信息
        String bucketDir = calibrationFileDto.getBucketDir();//压缩包所在目录
        String filename2 = calibrationFileDto.getFileName2();//原压缩包文件名
        File zip = new File(bucketDir + File.separator + filename2);//压缩包路径
        String unZipTmp = bucketDir + File.separator + filename2 + "_unzip";// 压缩包解压路径
        ZipUtil.unZip(zip, unZipTmp);//解压完成...

        //对解压目标文件夹里面的图片进行处理
        File unZipTmpFile = new File(unZipTmp);
        File[] listFiles = unZipTmpFile.listFiles();
        if (listFiles == null || listFiles.length == 0) {
            throw new Exception("压缩包为空");
        } else if (listFiles.length == 1 && listFiles[0].isDirectory()) {//解压出来后，如果里面只有一个文件夹
            // 解压出来后目标文件夹里面是一个文件夹(选择一个文件夹进行压缩时, 图片在所选文件夹里)
            File[] listFiles2 = listFiles[0].listFiles();
            if (listFiles2 == null || listFiles2.length == 0) {
                throw new Exception("压缩包为空");
            } else if (listFiles2.length != 1 && listFiles2[0].isDirectory()) {
                throw new Exception("压缩包里存在多个文件夹，请把所有图片放在一个文件夹里");
            }
            for (File file : listFiles2) {
                // 是图片文件才处理
                if (file.isFile() && ImageOperUtil.isImage(file.getName())) {
                    try (InputStream fIn = new FileInputStream(file);) {
                        CalibrationImgDto dto = saveThumbnailPicture(calibrationDto, calibrationFileDto, fIn, file.getName(), listFiles[0].getAbsolutePath());
                        if (dto != null) {
                            calibrationImgDtos.add(dto);
                        }
                    }
                }
                //file.delete(); // 处理完成删除文件
            }
            //listFiles[0].delete();
        } else if (listFiles.length != 1 && listFiles[0].isDirectory()) {
            throw new Exception("压缩包里存在多个文件夹，请把所有图片放在一个文件夹里");
        } else {
            // 解压出来后目标文件夹里是图片文件(选择所有图片进行压缩时)
            for (File file : listFiles) {
                // 是图片文件才处理，生成缩略图
                if (file.isFile() && ImageOperUtil.isImage(file.getName())) {
                    // 1.生成缩略图
                    // 2.生成对应的CalibrationImgDto,保存缩略图路径（需要关联calibrationFileDto）
                    InputStream fIn = new FileInputStream(file);
                    CalibrationImgDto dto = saveThumbnailPicture(calibrationDto, calibrationFileDto, fIn, file.getName(), unZipTmpFile.getAbsolutePath());
                    if (dto != null) {
                        calibrationImgDtos.add(dto);
                    }
                    fIn.close();
                }
                //file.delete(); // 原图文件不删
            }
        }
        // 解压文件夹不删
        //unZipTmpFile.delete();
        zip.delete();//解压完，删除zip包（有待商榷）
        //发布子任务和设置每个人的对应的素材
//			finisher = calibrationDto.getFinisher();
//			String[] finisherArr =null;
//			if(finisher.contains(",")){//多人
//				finisherArr = finisher.split(",");
//			}else{//单人
//				finisherArr[0] = finisher;
//			}

//			String newfinisher = finisher;
        if (StringUtils.isEmpty(finisher)) {
            finisher = calibrationDto.getFinisher();
        }
        String finishers[] = finisher.split(",");
        int userlength = finishers.length;
        for (int i = 0; i < calibrationImgDtos.size(); i++) {
            int j = i % userlength;
            calibrationImgDtos.get(i).setFinisher(finishers[j]);
        }

        //保存分割后的素材
        boolean tag = false;
        if (!calibrationImgDtos.isEmpty()) {
            tag = calibrationImgService.batchSave(calibrationImgDtos);
        }

        if (tag) { // 保存或更新发布任务和各个接收任务的数据
            tag = calibrationService.updateCalibrationAndCalibrationDetails(calibrationDto, finisher);
        }
        return tag;

//		} catch (IllegalArgumentException e) {
//			logger.error("上传图片异常", e);
//			String message = e.getMessage();
//			if ("图片名称太长".equals(message)) {
//				throw e;
//			}
//		} catch (IOException e) {
//			logger.error("上传zip文件异常", e);
//			throw e;
//		}
//		return false;
    }

    //	保存zip文件包
    public CalibrationFileDto saveZip(MultipartFile file, CalibrationDto calibrationDto) {

        String fileName = file.getOriginalFilename();//源文件名
        //防止上传重复文件报错，用UUID生成新的文件名
        String otherName = UUID.randomUUID().toString().replaceAll("-", "")
                + fileName.substring(fileName.lastIndexOf("."));

        String fileType = calibrationDto.getTaskType();
        String creater = calibrationDto.getCreater();

        String bucketDir = uploadPath + File.separator + "calibration" + File.separator + fileType + File.separator + creater;

        OutputStream os = null;
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            // 2、保存到临时文件
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流保存到本地文件
            File tempFile = new File(bucketDir);
            boolean results = tempFile.mkdirs();
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            os = new FileOutputStream(tempFile.getPath() + File.separator + otherName);
            // 开始读取
            while ((len = inputStream.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 完毕，关闭所有链接
            try {
                os.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        CalibrationFileDto calibrationFiles = new CalibrationFileDto();
        if (calibrationDto.getId() != null) {
            CalibrationFileDto calibrationFile = new CalibrationFileDto();
            calibrationFile.setBucketDir(bucketDir);
            calibrationFile.setCalibrationId(calibrationDto.getId());
            calibrationFile.setFileName(fileName);//源文件名
            calibrationFile.setFileName2(otherName);//UUID后的文件名（实际文件名）
            calibrationFile.setFileSize(file.getSize());

            calibrationFiles = calibrationFileService.save(calibrationFile);

        } else {
            return null;
        }


        return calibrationFiles;
    }

    /**
     * 利用解压后的文件输入流，保存原图文件和生成缩略图，返回CalibrationImgDto
     *
     * @param calibrationDto     标注任务信息
     * @param calibrationFileDto zip包文件
     * @param fileIn             图片文件输入流
     * @param originalFileName   原图片名
     * @param needThumbnail      是否需要缩略图
     * @return CalibrationImgDto
     */
    public CalibrationImgDto savePicture(CalibrationDto calibrationDto, CalibrationFileDto calibrationFileDto, InputStream fileIn, String originalFileName, boolean needThumbnail) {
        Assert.isTrue(originalFileName.length() < 200, "图片名称太长");
        CalibrationImgDto dto = new CalibrationImgDto();

        String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + getSuffix(originalFileName);
        String thumbnailRelativePath = null;
        String relativePath = null;
        //1.保存图片原图
        if (StringUtils.isNotEmpty(originalFileName)) {
            String pictureDir = calibrationFileDto.getBucketDir() + File.separator + calibrationFileDto.getId().toString() + File.separator + newFileName;
            File sourceFile = new File(pictureDir);
            File sourceParent = sourceFile.getParentFile();
            if (!sourceParent.exists()) {
                sourceParent.mkdirs();
            }
            relativePath = StringUtils.substringAfterLast(pictureDir, uploadPath);
            try (FileOutputStream fos = new FileOutputStream(sourceFile);) {

                //保存文件
                byte[] buff = new byte[1024];
                int len = -1;
                while ((len = fileIn.read(buff)) > 0) {
                    fos.write(buff, 0, len);
                }

                //2.生成、保存图片缩略图
                if (needThumbnail) {
                    String thumbnailPictureDir = calibrationFileDto.getBucketDir() + File.separator + calibrationFileDto.getId().toString() + "_thumbnail" + File.separator + newFileName;
                    if (uploadPath.contains("\\\\")) {//双反斜杠  换  单反斜杠
                        uploadPath = uploadPath.replace("\\\\", "\\");
                    }
                    thumbnailRelativePath = StringUtils.substringAfterLast(thumbnailPictureDir, uploadPath);
                    File thumbnailFile = new File(thumbnailPictureDir);

                    File thumbnailParent = thumbnailFile.getParentFile();
                    if (!thumbnailParent.exists()) {
                        thumbnailParent.mkdirs();
                    }
                    if (!thumbnailFile.exists()) {
                        thumbnailFile.createNewFile();
                    }
                    //生成缩略图
                    ImageOperUtil.genThumbnail(new FileInputStream(sourceFile), thumbnailWide, thumbnailHeight, thumbnailFile);

                    //生成CalibrationImgDto对象返回
                    //该http测试用
                    thumbnailPictureDir = "http://10.17.157.90/file/" +
                            "calibration" + File.separator + calibrationDto.getTaskType() + File.separator + calibrationDto.getCreater() +
                            File.separator + calibrationFileDto.getId().toString() + "_thumbnail" + File.separator + newFileName;
                    return generateCalibrationImgDto(calibrationDto.getCreater(), calibrationDto.getId(), calibrationFileDto.getId(),
                            originalFileName, pictureDir, thumbnailPictureDir, relativePath, thumbnailRelativePath);
                }
                return generateCalibrationImgDto(calibrationDto.getCreater(), calibrationDto.getId(), calibrationFileDto.getId(),
                        originalFileName, pictureDir, null, relativePath, null);
            } catch (IOException e) {
                logger.error("处理文件上传异常", e);
            }
        } else {
            logger.error("保存文件异常，MultipartFile获取文件名为空");
        }
        return null;
    }


    /**
     * 1.利用解压后的文件输入流，生成缩略图，
     * 2.填充并返回CalibrationImgDto(内含缩略图存放路径)
     *
     * @param calibrationDto     标注任务信息对象
     * @param calibrationFileDto zip包文件对象
     * @param fileIn             原图片文件输入流
     * @param originalFileName   原图片名
     * @param unZipPath          原图的解压路径
     * @return CalibrationImgDto
     */
    public CalibrationImgDto saveThumbnailPicture(CalibrationDto calibrationDto, CalibrationFileDto calibrationFileDto, InputStream fileIn, String originalFileName, String unZipPath) {
        Assert.isTrue(originalFileName.length() < 200, "图片名称太长");
        //1.保存图片原图
        if (StringUtils.isNotEmpty(originalFileName)) {
            //解压文件夹/原文件夹/thumbnail/缩略图1.jpg
            String thumbnailPictureDir = unZipPath + File.separator + "thumbnail" + File.separator + originalFileName;
            if (uploadPath.contains("\\\\")) {//双反斜杠  换  单反斜杠
                uploadPath = uploadPath.replace("\\\\", "\\");
            }
            String thumbnailRelativePath = StringUtils.substringAfterLast(thumbnailPictureDir, uploadPath);
            String relativePath = thumbnailRelativePath.replace("thumbnail" + File.separator, "");
            try {
                //2.生成、保存图片缩略图
                File thumbnailFile = new File(thumbnailPictureDir);

                File thumbnailParent = thumbnailFile.getParentFile();
                if (!thumbnailParent.exists()) {
                    thumbnailParent.mkdirs();
                }
                if (!thumbnailFile.exists()) {
                    thumbnailFile.createNewFile();
                }
                //生成缩略图
                ImageOperUtil.genThumbnail(fileIn, thumbnailWide, thumbnailHeight, thumbnailFile);

                //生成CalibrationImgDto对象返回
                return generateCalibrationImgDto(calibrationDto.getCreater(), calibrationDto.getId(), calibrationFileDto.getId(),
                        originalFileName, unZipPath + File.separator + originalFileName, thumbnailPictureDir, relativePath, thumbnailRelativePath);
            } catch (IOException e) {
                logger.error("处理文件上传异常", e);
            }
        } else {
            logger.error("保存文件异常，MultipartFile获取文件名为空");
        }
        return null;
    }

    /**
     * 获取文件名后缀
     *
     * @param fileName
     * @return
     */
    private String getSuffix(String fileName) {
        String suffix = "";
        if (!StringUtils.isEmpty(fileName) && fileName.indexOf('.') > 0) {
            suffix = fileName.substring(fileName.indexOf('.'));
        }
        return suffix;
    }

    private CalibrationImgDto generateCalibrationImgDto(String creater, Long calibrationId, Long calibrationFileId, String pictureName, String pictureDir, String thumbnailDir, String relativePath, String thumbnailRelativePath) {
        CalibrationImgDto dto = new CalibrationImgDto();
        dto.setCreater(creater);
        dto.setCalibrationId(calibrationId);
        dto.setCalibrationFileId(calibrationFileId);
        dto.setCompleted("0");
        dto.setPictureName(pictureName);
        dto.setPictureDir(pictureDir);
        dto.setThumbnailDir(thumbnailDir);
        dto.setRelativePath(relativePath);
        dto.setThumbnailRelativePath(thumbnailRelativePath);
        return dto;
    }

    public InputStream readFile(String fileDir) {
        try {
            return new FileInputStream(new File(fileDir));
        } catch (FileNotFoundException e) {
            logger.error("读取文件【" + fileDir + "】异常", e);
        }
        return null;
    }

    /**
     * 生成对应任务人的数据集的zip包
     *
     * @param calibrationImgDtoList
     * @param bucketdir
     * @param finisher
     * @return
     */
    @Deprecated
    public String createImgDetectCalibrationDetailZipFile(List<CalibrationImgDto> calibrationImgDtoList, String bucketdir, String finisher) {
        String zipFilePath = bucketdir + "dataset_" + finisher + "_" + System.currentTimeMillis();

        for (CalibrationImgDto calibrationImgDto : calibrationImgDtoList) {
            String originalPictureDir = calibrationImgDto.getPictureDir();
            if (StringUtils.isNotEmpty(originalPictureDir)) {
                File originalFile = new File(originalPictureDir);

                //String newPictureDir = bucketdir + File.separator + calibrationImgDto.getClassifyName() + File.separator + originalFile.getName();
                File newFile = new File(zipFilePath + File.separator + originalFile.getName());
                File sourceParent = newFile.getParentFile();
                if (!sourceParent.exists()) {
                    sourceParent.mkdirs();
                }
                try {
                    InputStream fin = new FileInputStream(originalFile);
                    FileOutputStream fos = new FileOutputStream(newFile);

                    //保存文件
                    byte[] buff = new byte[1024];
                    int len = -1;
                    while ((len = fin.read(buff)) > 0) {
                        fos.write(buff, 0, len);
                    }
                    fos.flush();
                    fos.close();
                    fin.close();
                } catch (IOException e) {
                    logger.error("创建文件异常", e);
                }
            } else {
                logger.error("保存文件异常，MultipartFile获取文件名为空");
            }
        }

        //TODO  这里的步骤，json文件是否需要更新？？


        //压缩成zip包
        ZipUtil.zipFileWithTier(zipFilePath, zipFilePath + ".zip");
        //删除目录
        try {
            FileUtils.forceDelete(new File(zipFilePath));
        } catch (IOException e) {
            logger.error("删除目录失败：" + zipFilePath, e);
            e.printStackTrace();
        }
        return zipFilePath + ".zip";

    }

    /**
     * 根据素材列表，生成压缩后的数据集zip包，返回zip文件路径
     *
     * @param calibrationImgDtoList 已标注的素材
     * @param materialFilePath      生成数据集的目录
     * @return 生成zip包的路径
     */
    public String createImgDetectMaterialZip(List<CalibrationImgDetectDto> calibrationImgDtoList, String materialFilePath) {
        //String zipFilePath = bucketdir + "dataset_"+finisher+"_"+System.currentTimeMillis() ;

        //复制图片到数据集目录
        long calibrationId = 0;
        for (CalibrationImgDetectDto calibrationImgDto : calibrationImgDtoList) {
            calibrationId = calibrationImgDto.getCalibrationId();
            String originalPictureDir = calibrationImgDto.getPictureDir();
            if (StringUtils.isNotEmpty(originalPictureDir)) {
                File originalFile = new File(originalPictureDir);

                //String newPictureDir = bucketdir + File.separator + calibrationImgDto.getClassifyName() + File.separator + originalFile.getName();
                File newFile = new File(materialFilePath + File.separator + originalFile.getName());
                File sourceParent = newFile.getParentFile();
                if (!sourceParent.exists()) {
                    sourceParent.mkdirs();
                }
                try {
                    InputStream fin = new FileInputStream(originalFile);
                    FileOutputStream fos = new FileOutputStream(newFile);

                    //保存文件
                    byte[] buff = new byte[1024];
                    int len = -1;
                    while ((len = fin.read(buff)) > 0) {
                        fos.write(buff, 0, len);
                    }
                    fos.flush();
                    fos.close();
                    fin.close();
                } catch (IOException e) {
                    logger.error("创建文件异常", e);
                }
            } else {
                logger.error("保存文件异常，MultipartFile获取文件名为空");
            }
        }

        //TODO  这里的步骤，json文件是否需要更新？？
        this.updateJsonTxt(calibrationImgDtoList, materialFilePath + File.separator + "json.txt");

        //压缩成zip包
        ZipUtil.zipFileWithTier(materialFilePath, materialFilePath + ".zip");
        //删除目录    待定
//		try {
//			FileUtils.forceDelete(new File(materialFilePath));
//		} catch (IOException e) {
//			logger.error("删除目录失败："+materialFilePath,e);
//			e.printStackTrace();
//		}
        return materialFilePath + ".zip";

    }

    private void updateJsonTxt(List<CalibrationImgDetectDto> imgs, String jsontxtPath) {
        //List<CalibrationImgDetectDto> imgs = calibrationObjectDetectionImgBoxApi.findCompletedByCalibrationId(calibrationId);

        StringBuilder sb = new StringBuilder();
        List<String> datas = new ArrayList<>();
        //String jsontxtPath = imgs.get(0).getBaseDir() + "json.txt";
        imgs.stream().forEach(item -> {
            //sb.append(item.getJsonTxt());
            datas.add(item.getJsonTxt());
        });
        File file = new File(jsontxtPath);
        try {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            try (FileOutputStream fos = new FileOutputStream(file)) {
                IOUtils.writeLines(datas, "\n", fos);
            }
            logger.info("jsontxt文件写入完成：" + jsontxtPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String createResultFile(List<CalibrationImgDto> calibrationImgDtoList, String bucketdir) {
        //生成对应文件夹和图片
        for (CalibrationImgDto calibrationImgDto : calibrationImgDtoList) {
            String originalPictureDir = calibrationImgDto.getPictureDir();
            if (StringUtils.isNotEmpty(originalPictureDir)) {
                File originalFile = new File(originalPictureDir);

                String newPictureDir = bucketdir + File.separator + calibrationImgDto.getClassifyName() + File.separator + originalFile.getName();
                File newFile = new File(newPictureDir);
                File sourceParent = newFile.getParentFile();
                if (!sourceParent.exists()) {
                    sourceParent.mkdirs();
                }
                try {
                    InputStream fin = new FileInputStream(originalFile);
                    FileOutputStream fos = new FileOutputStream(newFile);

                    //保存文件
                    byte[] buff = new byte[1024];
                    int len = -1;
                    while ((len = fin.read(buff)) > 0) {
                        fos.write(buff, 0, len);
                    }
                    fos.flush();
                    fos.close();
                    fin.close();
                } catch (IOException e) {
                    logger.error("创建文件异常", e);
                }
            } else {
                logger.error("保存文件异常，MultipartFile获取文件名为空");
            }
        }
        if (calibrationImgDtoList.size() == 0) {
            File bucketDirFile = new File(bucketdir);
            if (!bucketDirFile.exists()) {
                bucketDirFile.mkdirs();
            }
        }

        //压缩
        ZipUtil.zipFileWithTier(bucketdir, bucketdir + ".zip");
//		//删除目录    待定
//		try {
//			FileUtils.forceDelete(new File(bucketdir));
//		} catch (IOException e) {
//			logger.error("删除目录失败："+bucketdir,e);
//			e.printStackTrace();
//		}
        return bucketdir + ".zip";
    }
}
